<template>
  <el-dialog 
    :model-value="visible" 
    @update:model-value="$emit('update:visible', $event)" 
    :title="isEdit ? '编辑用户' : '新增用户'" 
    width="600px"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="头像" prop="avatarUrl">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarSelect"
        >
          <img v-if="fileList.length" :src="fileList[0].url" class="avatar">
          <img v-else-if="form.avatarUrl" :src="fileBaseUrl() + form.avatarUrl" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="avatar-tips">建议上传正方形图片，大小不超过2MB</div>
      </el-form-item>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="form.nickname" placeholder="请输入昵称" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="用户等级" prop="userLevel">
            <el-select v-model="form.userLevel" placeholder="请选择等级" style="width: 100%">
              <el-option label="普通用户" :value="1" />
              <el-option label="VIP用户" :value="2" />
              <el-option label="高级VIP" :value="3" />
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>
      
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="form.phoneNumber" placeholder="请输入手机号" :disabled="isEdit" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <!-- <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="积分" prop="points">
            <el-input-number v-model="form.points" :min="0" :max="999999" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> -->
      
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useFileUpload } from '@/composables/useFileUpload'
import { fileBaseUrl } from '@/apis/files'

const props = defineProps({
  visible: Boolean,
  user: { type: Object, default: () => ({}) },
  isEdit: Boolean
})

const emit = defineEmits(['update:visible', 'submit'])

const formRef = ref(null)
const loading = ref(false)

const form = reactive({
  userId: '',
  name: '',
  nickname: '',
  gender: '',
  phoneNumber: '',
  email: '',
  password: '',
  avatarUrl: '',
  userLevel: 1,
  points: 0,
  role: 'user'
})

const { fileList, uploadFile, replaceFile, deleteFile, clearFiles } = useFileUpload()

// 监听用户数据变化
watch(() => props.user, (val) => {
  if (val && Object.keys(val).length) {
    Object.assign(form, val)
    fileList.value = val.avatarUrl ? [{ url: fileBaseUrl() + val.avatarUrl, name: '头像' }] : []
  } else {
    Object.assign(form, {
      userId: '',
      name: '',
      nickname: '',
      gender: '',
      phoneNumber: '',
      email: '',
      password: '',
      avatarUrl: '',
      userLevel: 1,
      points: 0,
      role: 'user'
    })
    fileList.value = []
  }
}, { immediate: true })

// 处理头像选择
const handleAvatarSelect = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  // 创建文件预览
  const reader = new FileReader()
  reader.onload = () => {
    fileList.value = [{
      name: file.name,
      url: reader.result,
      raw: file.raw
    }]
  }
  reader.readAsDataURL(file.raw)

  return false // 阻止自动上传
}

// 关闭对话框
const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  clearFiles()
}

// 提交表单
const handleSubmit = async () => {
  await formRef.value.validate()
  loading.value = true
  
  try {
    // 处理头像上传
    if (fileList.value.length && fileList.value[0].raw) {
      if (props.isEdit && form.avatarUrl) {
        // 编辑时替换头像
        const result = await replaceFile(fileList.value[0], form.avatarUrl)
        if (result) {
          form.avatarUrl = result
        }
      } else {
        // 新增时上传头像
        const result = await uploadFile('user/avatar', fileList.value[0].raw)
        if (result) {
          form.avatarUrl = result
        }
      }
    }
    
    emit('submit', { ...form })
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { max: 20, message: '昵称长度不能超过 20 个字符', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  userLevel: [
    { required: true, message: '请选择用户等级', trigger: 'change' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}
</script>

<style scoped>
.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-tips {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: center;
}
</style> 